package com.cmd.user;

import java.net.InetSocketAddress;
import java.util.HashMap;
import java.util.Map;

import main.java.com.github.wxpay.sdk.WXPayUtil;

import com.alibaba.fastjson.JSONObject;
import com.mgr.UserPayMgr;
import com.mgr.UserVoucherMgr;
import com.player.User;
import com.qy.bean.PayInfo;
import com.qy.bean.Voucher;
import com.qy.bean.VoucherInfo;
import com.qy.mgr.VoucherMgr;
import com.qy.util.StaticData;
import com.util.AbstractCommand;
import com.util.PBMessage;
import com.util.QinYiWXPay;
import com.util.WXPayConfigImpl;

/**
 * 购买代金券
 * @author zwl
 * 2018年2月1日
 */
public class VoucherBuyCMD  extends AbstractCommand{

	@Override
	public void execute(User user, PBMessage packet) throws Exception {
		JSONObject reJs = new JSONObject();
		reJs.put(StaticData.reKey.cmd.getKey(),packet.getCode());
		JSONObject param = packet.getMessage();
		if(!param.containsKey("vType")){
			reJs.put(StaticData.reKey.code.getKey(), StaticData.codeType.param_error.getType());
			user.sendPacket(reJs);
			return;
		}
		/*
		 * 验证代金券是否存在
		 */
		int vId = param.getIntValue("vType");
		Voucher sv = VoucherMgr.getVoucher(vId);
		if(sv==null){
			reJs.put(StaticData.reKey.code.getKey(), StaticData.codeType.not_exist.getType());
			user.sendPacket(reJs);
			return;
		}
		/*
		 * 生成一张带付款的代金券
		 * 生成一个支付订单
		 * 然后生成预付订单参数给前端
		 */
		VoucherInfo vInfo = UserVoucherMgr.ceateVoucher(user.getID(), vId);
		
		PayInfo payInfo = UserPayMgr.createPay(user.getID(), StaticData.PayInfoType.VOUCHER_PAY.getType(), 
			vInfo.getId(),sv.getSellPrice(), vInfo.getId());
		
		vInfo.setPayId(payInfo.getId());
		UserVoucherMgr.updateUserVoucher(vInfo);
		
		QinYiWXPay qyp = new QinYiWXPay(sv.getSellPrice(), 
			((InetSocketAddress)user.getUserChannel().remoteAddress()).getAddress().getHostAddress(), 
			user.getOpenId(), payInfo.getLocalOrderNum());
		Map<String,String> payParam = qyp.doUnifiedOrder();
		
		Map<String, String> reqData = new HashMap<String, String>();
		reqData.put("timeStamp", Long.toString(WXPayUtil.getCurrentTimestamp()));
		reqData.put("package", "prepay_id="+payParam.get("prepay_id"));
		
		reqData.put("appId", WXPayConfigImpl.getInstance().getAppID());
		reqData.put("nonceStr", WXPayUtil.generateUUID());
		reqData.put("signType", "MD5");
		reqData.put("paySign", WXPayUtil.generateSignature(reqData,WXPayConfigImpl.getInstance().getKey()));
		reJs.put(StaticData.reKey.code.getKey(), StaticData.codeType.ok.getType());
		reJs.put(StaticData.reKey.cmd.getKey(),packet.getCode());
		reJs.putAll(reqData);
		user.sendPacket(reJs);
		return;
	}

}
